"use client"

import * as React from "react"
import { useState, useEffect } from "react"
import { 
  Select, 
  SelectContent, 
  SelectGroup, 
  SelectItem, 
  SelectLabel, 
  SelectTrigger, 
  SelectValue 
} from "@/components/ui/select"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { X, Plus, Search } from "lucide-react"

interface PBSLevel {
  id: number;
  level1_area: string;
  level2_category: string | null;
  level3_subitem: string;
  full_path: string;
  pbs_code: string;
  created_at?: string;
}

interface InstancePBSMapping {
  id: number;
  instance_id: string;
  pbs_level_id: number;
  pbs_instance_id: string;
  created_at: string;
}

interface PBSLevelSelectorProps {
  instanceId?: string;
  value?: number; // 当前选中的PBS层级ID
  onSelect?: (pbsLevelId: number, pbsInstanceId: string) => void;
  disabled?: boolean;
  placeholder?: string;
  className?: string;
}

export function PBSLevelSelector({
  instanceId,
  value,
  onSelect,
  disabled = false,
  placeholder = "选择PBS层级",
  className
}: PBSLevelSelectorProps) {
  const [pbsLevels, setPbsLevels] = useState<PBSLevel[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [selectedLevel, setSelectedLevel] = useState<PBSLevel | null>(null);
  
  // 三级选择状态
  const [selectedArea, setSelectedArea] = useState<string>("");
  const [selectedAnalysis, setSelectedAnalysis] = useState<string>("");
  const [selectedSubitem, setSelectedSubitem] = useState<string>("");

  // 获取所有PBS层级数据
  useEffect(() => {
    const fetchPBSLevels = async () => {
      try {
        setLoading(true);
        const response = await fetch('/api/pbs/levels');
        if (!response.ok) {
          throw new Error('获取PBS层级数据失败');
        }
        const data = await response.json();
        if (data.success) {
          setPbsLevels(data.data);
        } else {
          throw new Error(data.error || '获取PBS层级数据失败');
        }
      } catch (err) {
        console.error('获取PBS层级数据失败:', err);
        setError(err instanceof Error ? err.message : '获取PBS层级数据失败');
      } finally {
        setLoading(false);
      }
    };

    fetchPBSLevels();
  }, []);

  // 根据value查找对应的PBS层级并设置选择状态
  useEffect(() => {
    if (value && pbsLevels.length > 0) {
      const level = pbsLevels.find(l => l.id === value);
      if (level) {
        setSelectedLevel(level);
        setSelectedArea(level.level1_area);
        setSelectedAnalysis(level.level2_category || "");
        setSelectedSubitem(level.level3_subitem);
      }
    } else {
      // 清空选择状态
      setSelectedLevel(null);
      setSelectedArea("");
      setSelectedAnalysis("");
      setSelectedSubitem("");
    }
  }, [value, pbsLevels]);

  // 获取可选的区域列表
  const availableAreas = React.useMemo(() => {
    const areas = [...new Set(pbsLevels.map(level => level.level1_area))];
    return areas.sort();
  }, [pbsLevels]);

  // 根据选中的区域获取可选的分项
  const availableAnalysis = React.useMemo(() => {
    if (!selectedArea) return [];
    const analysisSet = new Set(
      pbsLevels
        .filter(level => level.level1_area === selectedArea && level.level2_category)
        .map(level => level.level2_category!)
    );
    return [...analysisSet].sort();
  }, [pbsLevels, selectedArea]);

  // 根据选中的区域和分项获取可选的子分项
  const availableSubitems = React.useMemo(() => {
    if (!selectedArea) return [];
    const subitems = pbsLevels
      .filter(level => 
        level.level1_area === selectedArea && 
        (!selectedAnalysis || level.level2_category === selectedAnalysis)
      )
      .map(level => level.level3_subitem);
    return [...new Set(subitems)].sort();
  }, [pbsLevels, selectedArea, selectedAnalysis]);

  // 处理区域选择
  const handleAreaSelect = (area: string) => {
    setSelectedArea(area);
    setSelectedAnalysis("");
    setSelectedSubitem("");
    setSelectedLevel(null);
  };

  // 处理分析项目选择
  const handleAnalysisSelect = (analysis: string) => {
    setSelectedAnalysis(analysis);
    setSelectedSubitem("");
    setSelectedLevel(null);
  };

  // 处理子分项选择
  const handleSubitemSelect = async (subitem: string) => {
    setSelectedSubitem(subitem);
    
    // 查找完整的PBS层级记录
    const level = pbsLevels.find(l => 
      l.level1_area === selectedArea &&
      (!selectedAnalysis || l.level2_category === selectedAnalysis) &&
      l.level3_subitem === subitem
    );
    
    if (!level || !instanceId) return;

    try {
      // 调用API为实例分配PBS层级并生成唯一ID
      const response = await fetch('/api/pbs/assign', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          instanceId,
          pbsLevelId: level.id
        })
      });

      if (!response.ok) {
        throw new Error('分配PBS层级失败');
      }

      const data = await response.json();
      if (data.success) {
        setSelectedLevel(level);
        onSelect?.(level.id, data.data.pbsInstanceId);
      } else {
        throw new Error(data.error || '分配PBS层级失败');
      }
    } catch (err) {
      console.error('分配PBS层级失败:', err);
      setError(err instanceof Error ? err.message : '分配PBS层级失败');
    }
  };

  // 清除选择
  const handleClearSelection = () => {
    setSelectedArea("");
    setSelectedAnalysis("");
    setSelectedSubitem("");
    setSelectedLevel(null);
    onSelect?.(0, '');
  };

  if (loading) {
    return (
      <div className={className}>
        <Label>PBS层级</Label>
        <div className="flex items-center justify-center p-4 text-sm text-muted-foreground">
          加载中...
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className={className}>
        <Label>PBS层级</Label>
        <div className="text-sm text-red-500 p-2 border border-red-200 rounded">
          {error}
        </div>
      </div>
    );
  }

  return (
    <div className={className}>
      <Label>PBS层级选择</Label>
      
      {/* 选中的PBS层级路径显示 */}
      {selectedLevel && (
        <div className="mt-2 mb-3">
          <Badge variant="secondary" className="inline-flex items-center gap-2">
            <span className="font-mono text-xs">{selectedLevel.pbs_code}</span>
            <span>{selectedLevel.full_path}</span>
            <Button
              variant="ghost"
              size="sm"
              className="h-4 w-4 p-0 hover:bg-destructive hover:text-destructive-foreground"
              onClick={handleClearSelection}
            >
              <X className="h-3 w-3" />
            </Button>
          </Badge>
        </div>
      )}

      {/* 三个下拉框在一行显示 */}
      <div className="mt-2 grid grid-cols-1 md:grid-cols-3 gap-3">
        {/* 第一级：区域选择 */}
        <div>
          <Label className="text-xs text-gray-600">区域</Label>
          <Select
            value={selectedArea}
            onValueChange={handleAreaSelect}
            disabled={disabled}
          >
            <SelectTrigger className="mt-1">
              <SelectValue placeholder="选择区域..." />
            </SelectTrigger>
            <SelectContent>
              {availableAreas.map((area) => (
                <SelectItem key={area} value={area}>
                  {area}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        {/* 第二级：分项选择 */}
        <div>
          <Label className="text-xs text-gray-600">分项</Label>
          <Select
            value={selectedAnalysis}
            onValueChange={handleAnalysisSelect}
            disabled={disabled || !selectedArea || availableAnalysis.length === 0}
          >
            <SelectTrigger className="mt-1">
              <SelectValue placeholder="选择分项..." />
            </SelectTrigger>
            <SelectContent>
              {availableAnalysis.map((analysis) => (
                <SelectItem key={analysis} value={analysis}>
                  {analysis}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        {/* 第三级：子分项选择 */}
        <div>
          <Label className="text-xs text-gray-600">子分项</Label>
          <Select
            value={selectedSubitem}
            onValueChange={handleSubitemSelect}
            disabled={disabled || !selectedArea}
          >
            <SelectTrigger className="mt-1">
              <SelectValue placeholder="选择子分项..." />
            </SelectTrigger>
            <SelectContent>
              {availableSubitems.map((subitem) => (
                <SelectItem key={subitem} value={subitem}>
                  <div className="flex flex-col items-start">
                    <span>{subitem}</span>
                    {(() => {
                      const level = pbsLevels.find(l => 
                        l.level1_area === selectedArea &&
                        (!selectedAnalysis || l.level2_category === selectedAnalysis) &&
                        l.level3_subitem === subitem
                      );
                      return level && (
                        <span className="text-xs text-muted-foreground font-mono">
                          {level.pbs_code}
                        </span>
                      );
                    })()}
                  </div>
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
      </div>

      {/* 选择进度提示 */}
      <div className="mt-2 text-xs text-muted-foreground">
        {!selectedArea && "请先选择区域"}
        {selectedArea && !selectedSubitem && `已选择区域：${selectedArea}，请继续选择子分项`}
        {selectedLevel && "选择完成！系统已为此实例生成唯一的层级ID"}
      </div>
    </div>
  );
}

// 简化版本 - 只显示当前选择的PBS层级
export function PBSLevelDisplay({ 
  pbsCode, 
  fullPath, 
  className 
}: { 
  pbsCode?: string; 
  fullPath?: string; 
  className?: string;
}) {
  if (!pbsCode || !fullPath) {
    return null;
  }

  return (
    <div className={className}>
      <Label>PBS层级</Label>
      <div className="mt-1">
        <Badge variant="outline" className="inline-flex items-center gap-2">
          <code className="text-xs">{pbsCode}</code>
          <span className="text-sm">{fullPath}</span>
        </Badge>
      </div>
    </div>
  );
}